<template>
  <el-scrollbar class="h-full">
    <el-form
      ref="formRef"
      v-loading="loading"
      :model="formState"
      :rules="rules"
      class="flex flex-col items-start gap-y-4"
      label-position="top"
      require-asterisk-position="right"
    >
      <QuoteCard header="管理端设置">
        <div class="max-w-[415px] pl-2">
          <el-form-item prop="admin_title">
            <template #label>
              <span class="text-black">管理端标题</span>
            </template>
            <small class="text-info leading-[12px] mb-3">
              展示位置：管理端登录页面、管理端浏览器标题及左上角管理端标题
            </small>
            <el-input
              v-model="formState.admin_title"
              maxlength="20"
              placeholder="请输入标题"
            ></el-input>
          </el-form-item>
          <el-form-item prop="admin_logos">
            <template #label>
              <span class="text-black">管理端Logo</span>
            </template>
            <div class="flex flex-col leading-normal gap-y-2 mb-6">
              <span>Logo图片</span>
              <small class="text-info">
                Logo图片支持上传png、jpg、jpeg、svg文件，上传图片大小不能超过2MB，图片大小建议为50px*50px
              </small>
            </div>
            <UploadLogo
              ref="adminUploadLogoRef"
              v-model="adminLogo"
            ></UploadLogo>
          </el-form-item>
        </div>
      </QuoteCard>
      <QuoteCard header="用户端设置">
        <div class="max-w-[415px] pl-2">
          <el-form-item prop="user_title">
            <template #label>
              <span class="text-black">用户端标题</span>
            </template>
            <small class="text-info leading-[1.5] mb-3">
              展示位置：用户端官网、用户端登录页面、用户端浏览器标题及左上角用户端标题
            </small>
            <el-input
              v-model="formState.user_title"
              maxlength="20"
              placeholder="请输入标题"
            ></el-input>
          </el-form-item>
          <el-form-item prop="user_logos">
            <template #label>
              <span class="text-black">用户端Logo</span>
            </template>
            <div class="flex flex-col leading-normal gap-y-2 mb-6">
              <span>Logo图片</span>
              <small class="text-info">
                Logo图片支持上传png、jpg、jpeg、svg文件，上传图片大小不能超过2MB，图片大小建议为50px*50px
              </small>
            </div>
            <UploadLogo ref="userUploadLogoRef" v-model="userLogo"></UploadLogo>
          </el-form-item>
          <el-form-item>
            <template #label>
              <span class="text-black">用户端备案信息</span>
            </template>
            <el-input
              v-model="formState.icp"
              placeholder="请输入ICP备案号"
            ></el-input>
          </el-form-item>
        </div>
      </QuoteCard>
      <el-button :disabled="disabled" type="primary" @click="handleSave">
        保存配置
      </el-button>
    </el-form>
  </el-scrollbar>
</template>

<script setup lang="ts">
import type { FormInstance, FormItemRule } from 'element-plus'

import type { CommonReturn } from '@/apis/model/_utils'
import { QuoteCard } from '@/components/application'
import { UploadLogo } from '@/components/business'
import { useAppStore } from '@/stores/modules/app'
import ToastUtils from '@/utils/toast'

const formRef = ref<FormInstance>()
const loading = ref(false)

const userUploadLogoRef = ref<InstanceType<typeof UploadLogo>>()
const adminUploadLogoRef = ref<InstanceType<typeof UploadLogo>>()

const disabled = computed(() => {
  if (!userUploadLogoRef.value || !adminUploadLogoRef.value) return false
  return userUploadLogoRef.value.loading || adminUploadLogoRef.value.loading
})

const rules: Record<string, FormItemRule[]> = {
  admin_title: [{ required: true, message: '请输入标题', trigger: 'blur' }],
  user_title: [{ required: true, message: '请输入标题', trigger: 'blur' }],
  admin_logos: [
    {
      required: true,
      validator(_, value) {
        if (!value?.length || (value?.length && !value[0].path)) {
          return new Error('请选择管理端logo')
        }
        return true
      },
      trigger: 'change'
    }
  ],
  user_logos: [
    {
      required: true,
      validator(_, value) {
        if (!value?.length || (value?.length && !value[0].path)) {
          return new Error('请选择用户端logo')
        }
        return true
      },
      trigger: 'change'
    }
  ]
}

type BasicConfig = Required<
  Required<CommonReturn<'/v1/system_config', 'get'>>['website_basic']
>

const appStore = useAppStore()

// 管理端logo
const adminLogo = ref('')
// 用户端logo
const userLogo = ref('')

const formState = ref<BasicConfig>({
  admin_logos: [],
  user_logos: [],
  admin_title: '',
  user_title: '',
  icp: ''
})

onMounted(() => {
  loading.value = true
  configInfoApi({})
    .then(res => {
      formState.value = res.website_basic as BasicConfig
      if (formState.value.admin_logos.length) {
        adminLogo.value = mergeBaseURL(formState.value.admin_logos[0].path)
      }
      if (formState.value.user_logos.length) {
        userLogo.value = mergeBaseURL(formState.value.user_logos[0].path)
      }
    })
    .finally(() => {
      loading.value = false
    })
})

const getImgPath = (path: string) => {
  if (!path) return ''
  const url = mergeBaseURL(path)
  const u = new URL(url)
  return u.pathname.replace(/^\//, '')
}

/**
 * 提交修改基础设置
 */
const handleSave = async () => {
  // 图片路径要去除域名前缀，只留下相对路径
  formState.value.admin_logos = [
    {
      is_default: 1,
      use_status: 1,
      name: 'logo',
      path: getImgPath(adminLogo.value)
    }
  ]
  formState.value.user_logos = [
    {
      is_default: 1,
      use_status: 1,
      name: 'logo',
      path: getImgPath(userLogo.value)
    }
  ]
  await formRef.value?.validate()
  loading.value = true
  try {
    await editConfigApi({
      website_basic: formState.value
    })
    appStore.getWebsiteConfig()
    ToastUtils.success('修改成功')
  } finally {
    loading.value = false
  }
}
</script>

<style lang="scss" scoped>
.text-info {
  display: inline-block;
  text-align: justify;
}

.el-form {
  :deep(.el-form-item__label) {
    padding: 0;
  }
}
</style>
